﻿using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Cngot.Extensions.Logger
{
    public class ServerIpEnricher : ILogEventEnricher
    {
        private const string ClientAgentPropertyName = "ServerIp";
        private const string ClientAgentItemKey = "Serilog_ServerIp";
        private static string serverIp = "";

        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            // var configration= httpContext.RequestServices.GetRequiredService<IConfiguration>();
            if (string.IsNullOrEmpty(serverIp))
            {
                NetworkInterface[] networks = NetworkInterface.GetAllNetworkInterfaces();
                List<string> serverIpAddresses = new List<string>();

                foreach (var network in networks)
                {
                    string ip = network.GetIPProperties().UnicastAddresses.Where(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address)).FirstOrDefault()?.Address.ToString();
                    if (!string.IsNullOrEmpty(ip))
                    {
                        serverIpAddresses.Add(ip);
                    }
                }
                serverIp = string.Join(",", serverIpAddresses);
            }

            var clientAgentProperty = new LogEventProperty(ClientAgentPropertyName, new ScalarValue(serverIp));

            logEvent.AddPropertyIfAbsent(clientAgentProperty);
        }
    }
}